#!/bin/bash

function chk_process() 
{
	SERVICE="$1"
	RESULT=`ps ax | sed -n /${SERVICE}/p`
	if [ "${RESULT:-null}" == null ]; then
		echo "$1 not running"
		return -1
	else
		echo "$1 running"
		return 1
	fi
}

#######################################################
# usage: mailer <send> <receiver> <title> <body file path>
#######################################################

function mailer {
MAIL="/usr/sbin/sendmail -t$1 -f$2"

SUBJECT=$3
BODY=$(/bin/cat $4)

${MAIL} << EOF
From: Sender <$1>
To: Receiver <$2>
Subject: ${SUBJECT}

${BODY}
EOF
}



function detect_pkg {
        if ! which $1 > /dev/null; then
                install_pkg $1
        fi
}

function install_pkg {
        apt-get -y install $1
}


function vdbench_filter()
{
        cat $1 | awk '{if (match($3,"avg_2-30")) print $2,$3,$5,$6,$9}' > $2 
	ifconfig eth0 >> $2
	hostname >> $2
	cat /proc/cpuinfo >> $2
}

usage()
{
cat << EOF
usage: $0 options

example: $0 -e myemail.example.com -d /dev/sdb -f vdbench.conf
This script installs vdbench and execute benchmarking.

OPTIONS:
   -h      Show this message
   -e      email address for receiving result
   -d      benchmark device (/dev/xvdb | /dev/hdb ..., default:/dev/xvdb)
   -f      config file (default:vdbench_short.conf)
   -v      Verbose
EOF
}

EMAIL=
DEV="/dev/xvdb"
VERBOSE=
CONF=vdbench_short.conf
while getopts "he:d:f:v" OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
         e)
             EMAIL=$OPTARG
             ;;
         d)
             DEV=$OPTARG
             ;;
         v)
             VERBOSE=1
             ;;
         f)
             CONF=$OPTARG
             ;;   	
         ?)
             usage
             exit
             ;;
     esac
done



function install_vdbench()
{

	detect_pkg wget
	detect_pkg tcsh
	install_pkg openjdk-6-jre 
	detect_pkg unzip

	rm -rf /tmp/vdbench*

	echo "Download vdbench source....."

	wget -T 3 -t 1 -q -P /tmp https://conf.googlecode.com/files/vdbench502.zip

	sleep 10 

	echo "Unzip vdbench source....."
	mkdir /tmp/vdbench/
	unzip /tmp/vdbench502.zip -d /tmp/vdbench/

	echo "Download vdbench configuration file....."
	wget -O /tmp/vdbench/vdbench.conf http://conf.googlecode.com/svn/trunk/benchmark/$1

}

function execute_vdbench()
{
cd /tmp/vdbench

echo "Update test disk($2)...."
sed 's,DISK,'$2',g' /tmp/vdbench/vdbench.conf > /tmp/vdbench/vdbench1.conf

echo "Executing Vdbench ...."
/tmp/vdbench/vdbench -f /tmp/vdbench/vdbench1.conf


RESULT="/tmp/vdbench/output/flatfile.html"
OUTPUT="/tmp/vdbench/output/result"
vdbench_filter ${RESULT} ${OUTPUT}
mailer vdbench@conf.googlecode.com $1 vdbench ${OUTPUT}
}

#install_vdbench

if [[ -z $EMAIL ]]
then
	usage
	exit 1
fi
install_vdbench $CONF
execute_vdbench $EMAIL $DEV
